package com.motion.controller;


import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.motion.dto.HealthRecordDto;
import com.motion.dto.UserAbbDto;
import com.motion.dto.UserLoginDto;
import com.motion.dto.UserRetDto;
import com.motion.generator.entity.*;
import com.motion.result.Result;
import com.motion.result.ResultFactory;
import com.motion.service.UserDataService;
import com.motion.service.UserFocusService;
import com.motion.service.UserService;
import io.swagger.annotations.Api;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

@RestController
@RequestMapping("/api/community")
@Api("社区模块")
public class CommunityController {
    @Autowired
    private UserFocusService userFocusService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserDataService userDataService;
//    @Autowired
//    private UserAbbDto userId2UserAbb(Long user1, Long user2)


    @RequestMapping(value = "/focusOn", method = RequestMethod.GET)
    public Result focusOn(@RequestParam String token, @RequestParam("userId") Long usr, @RequestParam int relation){
        if(StpUtil.getLoginIdByToken(token)==null){
            return ResultFactory.buildResultTokenError("token无效");
        }
        Long userId = Long.valueOf(String.valueOf(StpUtil.getLoginIdByToken(token)));
//        Long userId = 2L;

        if(relation % 2 == 0){
            //陌生人或粉丝
            UserFocus userFocus = new UserFocus();
            userFocus.setUserId(userId);
            userFocus.setFocusedUserId(usr);
            userFocus.setCreateTime(new Date().toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime());
            userFocusService.createFocus(userFocus);
        }

        return ResultFactory.buildSuccessResult(null);
    }

    @RequestMapping(value = "/cancelFocus", method = RequestMethod.GET)
    public Result CancelFocus(@RequestParam String token, @RequestParam("userId") Long usr, @RequestParam int relation){
        if(StpUtil.getLoginIdByToken(token)==null){
            return ResultFactory.buildResultTokenError("token无效");
        }
        Long userId = Long.valueOf(String.valueOf(StpUtil.getLoginIdByToken(token)));
//        Long userId = 2L;
        //简单起见，直接删掉记录
        if(relation % 2 == 1){//关注或好友
            userFocusService.cancelFocus(userId, usr);
        }
        return ResultFactory.buildSuccessResult(null);
    }

    @RequestMapping(value = "/getFocusList", method = RequestMethod.GET)
    public Result getFocusList(@RequestParam String token, @RequestParam Long currentPage){
        if(StpUtil.getLoginIdByToken(token)==null){
            return ResultFactory.buildResultTokenError("token无效");
        }
        Long userId = Long.valueOf(String.valueOf(StpUtil.getLoginIdByToken(token)));
//        Long userId = 2L;

        IPage<UserFocus> userFocusPage = userFocusService.getFocus(userId, currentPage, 10L);

        UserRetDto userRetDto = new UserRetDto();
        userRetDto.setTotalPages(userFocusPage.getPages());
        userRetDto.setHasNext(userFocusPage.getPages()>currentPage);

        List<UserAbbDto> userAbbDtoList = new LinkedList<>();
        for(UserFocus usr: userFocusPage.getRecords()){
            userAbbDtoList.add(userId2UserAbb(userId, usr.getFocusedUserId()));
        }
        userRetDto.setUserAbbList(userAbbDtoList);
        return ResultFactory.buildSuccessResult(userRetDto);
    }

    @RequestMapping(value = "/getFansList", method = RequestMethod.GET)
    public Result getFansList(@RequestParam String token, @RequestParam Long currentPage){
        if(StpUtil.getLoginIdByToken(token)==null){
            return ResultFactory.buildResultTokenError("token无效");
        }
        Long userId = Long.valueOf(String.valueOf(StpUtil.getLoginIdByToken(token)));
//        Long userId = 2L;

        IPage<UserFocus> userFocusPage = userFocusService.getFans(userId, currentPage, 10L);

        UserRetDto userRetDto = new UserRetDto();
        userRetDto.setTotalPages(userFocusPage.getPages());
        userRetDto.setHasNext(userFocusPage.getPages()>currentPage);

        List<UserAbbDto> userAbbDtoList = new LinkedList<>();
        for(UserFocus usr: userFocusPage.getRecords()){
            userAbbDtoList.add(userId2UserAbb(userId, usr.getUserId()));
        }
        userRetDto.setUserAbbList(userAbbDtoList);

        return ResultFactory.buildSuccessResult(userRetDto);
    }

    private UserAbbDto userId2UserAbb(Long user1, Long user2){
        User user = userService.getUserById(user2);
        UserAbbDto userAbbDto= new UserAbbDto();

        userAbbDto.setNickName(user.getNickName());
        userAbbDto.setHeadPortrait(user.getHeadPortrait());
        userAbbDto.setRelation(userFocusService.getRelation(user1, user2));
        userAbbDto.setUserId(user2);
        return userAbbDto;
    }


    //获取用户基本信息
    @RequestMapping(value = "/getUserdata", method = RequestMethod.GET)
    public Result getUserdata(@RequestParam String token){
        //假token
        if(StpUtil.getLoginIdByToken(token)==null){
            return ResultFactory.buildResultTokenError("token无效");
        }
        Long userId=Long.valueOf(String.valueOf(StpUtil.getLoginIdByToken(token)));
//        Long userId=Long.valueOf(token);
        return ResultFactory.buildSuccessResult(userService.getUserById(userId));
    }
    //设置用户基本信息
    @RequestMapping(value = "/saveUserdata", method = RequestMethod.POST)
    public Result setUserdata(@RequestBody User user){
        System.out.println(user.getHeadPortrait());
        String token=user.getToken();
        if(StpUtil.getLoginIdByToken(token)==null){
            return ResultFactory.buildResultTokenError("token无效");
        }
        Long userId=Long.valueOf(String.valueOf(StpUtil.getLoginIdByToken(token)));
//        Long userId=Long.valueOf(token);
        user.setUserId(userId);
        userService.updateUser(user);
        return ResultFactory.buildSuccessResult(userService.getUserById(user.getUserId()));
    }
    @RequestMapping(value = "/saveHealthRecord", method = RequestMethod.POST)
    private Result saveHealthRecord(@RequestBody UserLoginDto healthData){
        if(StpUtil.getLoginIdByToken(healthData.getToken())==null){
            return ResultFactory.buildResultTokenError("token无效");
        }
        UserData userData=new UserData();
        userData.setHeight(healthData.getHeight());
        userData.setWeight(healthData.getWeight());
        userData.setUserId(Long.valueOf(String.valueOf(StpUtil.getLoginIdByToken(healthData.getToken()))));
        userData.setRecordTime(LocalDateTime.now());
        return ResultFactory.buildSuccessResult(userDataService.insertHealthData(userData));
    }
    @RequestMapping(value = "/getHealthRecord", method = RequestMethod.GET)
    private Result getHealthRecord(@RequestParam String token,@RequestParam Long page,@RequestParam Long size){
        if(StpUtil.getLoginIdByToken(token)==null){
            return ResultFactory.buildResultTokenError("token无效");
        }
        Long useId=Long.valueOf(String.valueOf(StpUtil.getLoginIdByToken(token)));
        IPage<UserData> userDataList=userDataService.getUserDataList(useId,page,size);
        HealthRecordDto resulf=new HealthRecordDto();
        resulf.setHealthRecord(userDataService.userData2RecordHealth(userDataList.getRecords()));
        resulf.setHasNext(page*size<userDataList.getTotal());
        return ResultFactory.buildSuccessResult(resulf);
    }
}
